class nhnl_r:
    def __init__(self,timeperiod=250,mintimeperiod=60,price="close",fx="high"):
        self.timeperiod=timeperiod
        self.mintimeperiod=mintimeperiod
        self.price=price
        self.fx=fx
        self.data=[]
        self.timekey=None

    def oncalc(self, b,timekey=None):
        rst = None
        if b   is not None:
            timekey = b["timekey"]
            price=b[self.price]
            if not price:
                if self.data:
                    price=self.data[-1]
            if timekey   is not None:
                if timekey == self.timekey:
                    self.data[-1] = price
                else:
                    self.data.append(price)
                    self.timekey = timekey
            else:
                self.data.append(price)
            if len(self.data) > self.timeperiod:
                self.data.pop(0)
            if len(self.data) >= self.mintimeperiod:
                if self.fx=="high":
                    p0=max(self.data)
                    rst= 1 - price / p0
                else:
                    p0=min(self.data)
                    rst= price / p0-1
        return rst
